package com.yanhao.viewmode

import android.util.Log
import androidx.lifecycle.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yanhao.bean.Chapters
import com.yanhao.bean.WanResult
import com.yanhao.etx.error
import com.yanhao.repository.WxarticleFfRepository
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.lang.IllegalArgumentException

class WxarticleFfViewModel(private val repository: WxarticleFfRepository) : BaseViewModel() {
    private var _chapters = MutableLiveData<MutableList<Chapters>>()
    val chapters: LiveData<MutableList<Chapters>> = _chapters

    private var _wxarticleId = MutableLiveData<Int>()
    val wxarticleId: LiveData<Int>
        get() = _wxarticleId

    fun setWxarticleId(wxarticleId: Int) {
        _wxarticleId.value = wxarticleId
    }

    //数据下标页
    private var _indexPager = MutableLiveData<Int>(1)
    val indexPager: LiveData<Int> = _indexPager

    //刷新数据
    fun refreshCurrent(id: Int) {
        _indexPager.value = 1
        getWxarticleDatas(id)
    }

    //加载更多
    fun onLoadMoreCurrent(id: Int) {
        val index = _indexPager.value ?: 1
        val result = index.plus(1)
        _indexPager.value = result
        getMoreWxarticleDatas(id)
    }

    //获取当前公众号下属数据
    fun getWxarticleDatas(id: Int) {
//        viewModelScope.launch(CoroutineExceptionHandler { _, e ->
//            Log.e(
//                "TAG",
//                "异常是:${e.message} ",
//
//            ) }) {
//            runCatching {
//                repository.getWxarticleDatas(id, _indexPager.value ?: 1)
//            }.onFailure {
//                Log.e("getWxarticleDatas", "错误是: ${it.message}")
//            }.onSuccess {
//                if (it.errorCode == 0) {
//                        _chapters.postValue(it.data.datas)
//                }
//            }


//       flow异常捕获
//        .catch { e: Throwable ->
//            if (e is HttpException) {
//                var errorBody = e.response()?.errorBody()
//                var errorJson = errorBody?.string()
//                val type = object : TypeToken<WanResult<Boolean>>() {}.type
//                val result = Gson().fromJson<WanResult<Boolean>>(errorJson, type)
////                    Log.e(
////                        "TAG",
////                        "错误code= ${e.code()} msg= ${e.message()} err: =${errorJson} json解析对象是:${result}"
////                    )
//                _msg.value = result.content
//            } else if (e is InterruptedIOException) {
//                _msg.value = ErrorMsg.TIMEOUT
//            } else {
//                _msg.value = ErrorMsg.FLOWCACTC
//            }
//            _loadding.value = false
//        }

        viewModelScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
            Log.e("TAG", "getWxarticleDatas: 异常是 ${throwable}")
        }) {
            flow {
                val result = repository.getWxarticleDatas(id, _indexPager.value ?: 1)
                emit(result)
            }.flowOn(Dispatchers.IO)
                .onStart {

                }.catch { e: Throwable ->
                    errorCatch(e)
                }.onCompletion {

                }.collect {
                    it?.let {
                        if (it.errorCode == 0) {
                            _chapters.value?.clear()
                            //说明是第一页
                            _chapters.value = it.data.datas
                        }
                    }
                }
        }
    }

    fun getMoreWxarticleDatas(id: Int) {
        viewModelScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
            Log.e("TAG", "getWxarticleDatas: 异常是 ${throwable}")
        }) {
            flow {
                val result = repository.getWxarticleDatas(id, _indexPager.value ?: 1)
                emit(result)
            }.flowOn(Dispatchers.IO)
                .onStart {

                }.catch {

                }.onCompletion {

                }.collect {
                    it?.let {
                        if (it.errorCode == 0) {
                            val list = _chapters.value
                            list?.addAll(it.data.datas)
                            list?.let {
                                _chapters.value = it
                            }
                        }
                    }
                }
        }
    }

    fun collectArticle(id: Long) {
        val list = _chapters.value
        list?.map {
            if (it.id == id) {
                if (it.collect) {
                    it.copy(collect = false)
                } else {
                    it.copy(collect = true)
                }
            } else {
                it
            }
        }?.toMutableList().let {
            _chapters.postValue(it)
        }
    }

}

class WxarticleFfViewModelFactory() : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(WxarticleFfViewModel::class.java)) {
            return WxarticleFfViewModel(repository = WxarticleFfRepository()) as T
        }
        throw IllegalArgumentException("不能找到 WxarticleFfRepository ")
    }

}